package com.wwz.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwz.feign.FileClients;
import com.wwz.mapper.HouseMapper;
import com.wwz.pojo.FileInfo;
import com.wwz.pojo.House;
import com.wwz.pojo.User;
import com.wwz.pojo.query.HouseQuery;
import com.wwz.util.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 房产信息接口实现
 *
 * @date 2022/03/24 26:02:48
 */
@Service
public class HouseServiceImpl extends ServiceImpl<HouseMapper, House> implements IHouseService {

    @Resource
    private FileClients fileClients;

    @Resource
    private IUserService userService;

    @Override
    public IPage<House> toPage(HouseQuery query) {
        LambdaQueryWrapper<House> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(query.getMaster())) {
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName,query.getMaster()));
            if (user != null) {
                wrapper.like(House::getMaster, user.getId());
            }
        }
        wrapper.orderByDesc(House::getCreateTime);

        IPage<House> page = this.page(query.toPage(), wrapper);

        List<FileInfo> files = fileClients.fileList().getResult();
        Map<String, List<FileInfo>> fileMap = null;
        if (CollUtil.isNotEmpty(files)) {
            fileMap = files.stream().collect(Collectors.groupingBy(FileInfo::getDataId));
        }
        for (House record : page.getRecords()) {
            List<FileInfo> fileInfos = null;
            if (fileMap != null) {
                fileInfos = fileMap.get(record.getDataId());
            }
            User user1 = userService.getById(record.getMaster());
            if (CollUtil.isNotEmpty(fileInfos) && fileInfos != null) {
                record.setFileInfo(fileInfos.get(0));
            }
            if (user1 != null) {
                record.setMaster(user1.getUserName());
            }
        }
        return page;
    }

    @Override
    public void addOrUpdate(House house) {

        House one = this.getById(house.getId());
        if (one == null) {
            house.setId(StrUtil.uuid());
            house.setCreateTime(new Date());
            save(house);
            return;
        }

        updateById(house);
    }
}
